import React, { useEffect, useState } from 'react';
import {
  Table,
  Card,
  Button,
  Space,
  Modal,
  message,
  Popconfirm,
  Descriptions,
  Tag,
} from 'antd';
import {
  EyeOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
  SendOutlined,
} from '@ant-design/icons';
import { getAllOrders, deleteOrder, updateOrderStatus } from '../../../services/mockOrderService';
import { Order, OrderStatus, OrderItem } from '../../../types/order';

const OrderManagement: React.FC = () => {
  const [orders, setOrders] = useState<Order[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedOrder, setSelectedOrder] = useState<Order | null>(null);
  const [modalVisible, setModalVisible] = useState(false);

  // 获取订单列表
  const fetchOrders = async () => {
    setLoading(true);
    try {
      const data = await getAllOrders();
      setOrders(data);
    } catch (error) {
      message.error('获取订单列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchOrders();
  }, []);

  // 查看订单详情
  const handleViewOrder = (order: Order) => {
    setSelectedOrder(order);
    setModalVisible(true);
  };

  // 删除订单
  const handleDeleteOrder = async (orderId: string) => {
    try {
      await deleteOrder(orderId);
      message.success('删除成功');
      fetchOrders(); // 刷新列表
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 发货处理函数
  const handleShipOrder = async (orderId: string) => {
    try {
      await updateOrderStatus(orderId, OrderStatus.SHIPPED);
      message.success('订单已发货');
      fetchOrders(); // 刷新列表
    } catch (error) {
      message.error('发货失败');
    }
  };

  // 订单状态映射
  const statusMap = {
    [OrderStatus.PENDING]: { text: '待付款', color: 'warning' },
    [OrderStatus.PAID]: { text: '已付款', color: 'processing' },
    [OrderStatus.SHIPPED]: { text: '已发货', color: 'success' },
    [OrderStatus.COMPLETED]: { text: '已完成', color: 'success' },
    [OrderStatus.CANCELLED]: { text: '已取消', color: 'error' },
  };

  // 支付方式映射
  const paymentMethodMap = {
    'alipay': '支付宝',
    'wechat': '微信支付',
    'bank': '银行卡支付'
  };

  const columns = [
    {
      title: '订单号',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (time: string) => new Date(time).toLocaleString(),
    },
    {
      title: '总金额',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      render: (amount: number) => `¥${amount !== undefined ? amount.toFixed(2) : '0.00'}`,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: OrderStatus) => (
        <Tag color={statusMap[status].color}>{statusMap[status].text}</Tag>
      ),
    },
    {
      title: '支付方式',
      dataIndex: 'paymentMethod',
      key: 'paymentMethod',
      render: (method: string, record: Order) => {
        // 如果订单未支付，显示为空
        if (record.status === OrderStatus.PENDING) {
          return '-';
        }
        // 如果已支付但没有支付方式，显示未知
        if (!method) {
          return '未知';
        }
        // 显示支付方式
        return paymentMethodMap[method as keyof typeof paymentMethodMap] || method;
      },
    },
    {
      title: '收货人',
      dataIndex: ['address', 'name'],
      key: 'receiver',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Order) => (
        <Space>
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => handleViewOrder(record)}
          >
            查看
          </Button>
          {record.status === OrderStatus.PAID && (
            <Popconfirm
              title="确定要将此订单标记为已发货吗？"
              onConfirm={() => handleShipOrder(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Button type="link" icon={<SendOutlined />}>
                发货
              </Button>
            </Popconfirm>
          )}
          <Popconfirm
            title="确定要删除这个订单吗？"
            description="删除后无法恢复"
            onConfirm={() => handleDeleteOrder(record.id)}
            okText="确定"
            cancelText="取消"
            icon={<ExclamationCircleOutlined style={{ color: 'red' }} />}
          >
            <Button type="link" danger>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div className="order-management">
      <Card title="订单管理">
        <Table
          columns={columns}
          dataSource={orders}
          rowKey="id"
          loading={loading}
        />
      </Card>

      <Modal
        title="订单详情"
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={800}
      >
        {selectedOrder && (
          <div>
            <h3>基本信息</h3>
            <p>订单号：{selectedOrder.id}</p>
            <p>创建时间：{new Date(selectedOrder.createTime).toLocaleString()}</p>
            <p>总金额：¥{selectedOrder.totalAmount !== undefined ? selectedOrder.totalAmount.toFixed(2) : '0.00'}</p>
            <p>状态：<Tag color={statusMap[selectedOrder.status].color}>
              {statusMap[selectedOrder.status].text}
            </Tag></p>
            <p>支付方式：{selectedOrder.status === OrderStatus.PENDING ? '-' : 
              paymentMethodMap[selectedOrder.paymentMethod as keyof typeof paymentMethodMap] || 
              (selectedOrder.paymentMethod || '未知')}</p>

            <h3>收货信息</h3>
            <p>收货人：{selectedOrder.address.name}</p>
            <p>电话：{selectedOrder.address.phone}</p>
            <p>地址：{selectedOrder.address.province} {selectedOrder.address.city} {selectedOrder.address.district} {selectedOrder.address.detail}</p>

            <h3>商品信息</h3>
            <Table
              dataSource={selectedOrder.items}
              rowKey="id"
              pagination={false}
              columns={[
                {
                  title: '商品名称',
                  dataIndex: 'name',
                  key: 'name',
                },
                {
                  title: '单价',
                  dataIndex: 'price',
                  key: 'price',
                  render: (price: number) => `¥${price.toFixed(2)}`,
                },
                {
                  title: '数量',
                  dataIndex: 'quantity',
                  key: 'quantity',
                },
                {
                  title: '小计',
                  key: 'subtotal',
                  render: (_: any, record: OrderItem) => `¥${(record.price * record.quantity).toFixed(2)}`,
                },
              ]}
            />
          </div>
        )}
      </Modal>
    </div>
  );
};

export default OrderManagement; 